//
//  HomeWorkContentViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/15.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class HomeWorkContentViewController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,MWPhotoBrowserDelegate,UITableViewDelegate,UITableViewDataSource {

    var titleLabel,timeLabel,contentLbel: UILabel!
    var photoCollectionView: UICollectionView!
    var tableView: UITableView!
    var tableFoot: UILabel!
    
    var commentArray = NSMutableArray()
    
    var dic: JSON!
    let imageArray = NSMutableArray()
    var photoArray = NSMutableArray()
    var index1: String!
    let collectionIdentifier = "PicCollectionViewCellIdentifier"
    
    var hud: MBProgressHUD!
    
    var apiulr = ""
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.title = "作业详情"
        self.view.backgroundColor = UIColor.init(hexString: "f0f0f0", alpha: 1)
        
        InitViews()
        getData()
        NotificationCenter.default.addObserver(self, selector: #selector(HomeWorkContentViewController.showBigImage(_:)), name: NSNotification.Name(rawValue: "showBigImage"), object: nil)
    }

    func InitViews() {
        
        let title = dic["title"].stringValue.removingPercentEncoding!
        let content = dic["contents"].stringValue.removingPercentEncoding!
        let time = dic["edittime"].stringValue
        let classname = dic["ClassName"].stringValue
        let url = dic["url"].stringValue
        let sender = dic["publisher"].stringValue
        let edittime = time.components(separatedBy: "T")[0]
        let array = url.components(separatedBy: "|")
        let count = String(array.count)
        
        let tableHeader = UIView.init()
        tableHeader.backgroundColor = UIColor.white
        var height: CGFloat = 0
        
        titleLabel = UILabel.init(frame: CGRect(x: 0, y: 10, width: screenW, height: 30))
        titleLabel.font = UIFont.boldFlatFont(ofSize: 16)
        titleLabel.textColor = UIColor.darkGray
        titleLabel.textAlignment = NSTextAlignment.center
        titleLabel.text = title
        
        tableHeader.addSubview(titleLabel)
        
        timeLabel = UILabel.init(frame: CGRect(x: 10, y: titleLabel.frame.maxY, width: screenW - 20, height: 20))
        timeLabel.font = UIFont.systemFont(ofSize: 14)
        timeLabel.textColor = textlight
        timeLabel.text = "\(classname) \(sender)老师 发表于\(edittime)"
        tableHeader.addSubview(timeLabel)
        
        contentLbel = UILabel.init(frame: CGRect(x: 10, y: timeLabel.frame.maxY + 10, width: screenW - 20, height: getLabelHeight(content, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 20)))
        contentLbel.numberOfLines = 0
        contentLbel.textColor = textlight
        contentLbel.font = UIFont.systemFont(ofSize: 14)
        contentLbel.text = content
        tableHeader.addSubview(contentLbel)
        
        height = 10 + 30 + 20 + 10 + getLabelHeight(content, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 20) + 5
        
        if count != "0" {
            if url.characters.count != 0{
                imageArray.addObjects(from: array)
                let line = UIView.init(frame: CGRect(x: 20, y: contentLbel.frame.maxY + 20, width: screenW - 40, height: 1))
                line.backgroundColor = UIColor.init(hexString: "eeeeee", alpha: 1)
                let label = UILabel.init(frame: CGRect(x: (screenW - 50)/2, y: contentLbel.frame.maxY + 10, width: 50, height: 20))
                label.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
                label.textAlignment = NSTextAlignment.center
                label.textColor = textlight
                label.font = UIFont.systemFont(ofSize: 14)
                label.text = "附件"
                
                photoCollectionView = UICollectionView.init(frame: CGRect(x: 15, y: label.frame.maxY+10, width: screenW - 30, height: getPhotoCollectionHeight(imageArray)), collectionViewLayout: photoFlowLayout.init())
                photoCollectionView.backgroundColor = UIColor.clear
                photoCollectionView.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
                photoCollectionView.scrollsToTop = true
                photoCollectionView.delegate = self
                photoCollectionView.dataSource = self
                
                tableHeader.addSubview(line)
                tableHeader.addSubview(label)
                tableHeader.addSubview(photoCollectionView)
                height += 30 + getPhotoCollectionHeight(imageArray)
            }
        }
        
        tableHeader.frame = CGRect(x: 0, y: 0, width: screenW, height: height)
        
        tableFoot = UILabel.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 100))
        tableFoot.font = UIFont.systemFont(ofSize: 14)
        tableFoot.textAlignment = NSTextAlignment.center
        tableFoot.textColor = UIColor.init(hexString: "9B9B9B", alpha: 1)
        if commentArray.count == 0{
            tableFoot.text = "暂时还没有回复"
        }
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = tableHeader
        tableView.tableFooterView = tableFoot
        tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        self.view.addSubview(tableView)
    }
    func getData() {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.animationType = MBProgressHUDAnimation.fade
        
        let serid = dic["ID"].stringValue
        let request = "\(requestHeader)32</t><hwid>\(serid)</hwid></channel></rss>"
        let url = server + adminwebapppi
        HttpPostUTF(url, requestXML: request) { (data, result, error) in
            if error == nil {
                self.commentArray = NSMutableArray()
               
                let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]
                if array.count != 0 {
                    for i in 0..<array.count {
                        let dic = array[i]
                        let Msg = dic["Msg"].stringValue
                        let Url = dic["Url"].stringValue
                        let edittime = dic["edittime"].stringValue
                        let usertype = dic["usertype"].stringValue
                        let userphoto = dic["userphoto"].stringValue
                        let UserName = dic["UserName"].stringValue
                        let dicitonary: NSDictionary = ["Msg" : Msg, "Url" : Url, "edittime" : edittime, "usertype": usertype, "userphoto" : userphoto, "UserName" : UserName]
                        self.commentArray.add(dicitonary)
                        let aclist1 = dic["aclist1"]
                        if aclist1.count != 0 {
                            for i in 0..<aclist1.count {
                                let dic = aclist1[i]
                                let Msg = dic["Msg"].stringValue
                                let Url = dic["Url"].stringValue
                                let edittime = dic["edittime"].stringValue
                                let usertype = dic["usertype"].stringValue
                                let userphoto = dic["userphoto"].stringValue
                                let UserName = dic["UserName"].stringValue
                                let dicitonary: NSDictionary = ["Msg" : Msg, "Url" : Url, "edittime" : edittime, "usertype": usertype, "userphoto" : userphoto, "UserName" : UserName]
                                self.commentArray.add(dicitonary)
                            }
                        }
                    }
                    self.tableView.tableFooterView = UIView()
                    
                }
                self.tableView.reloadData()
                self.hud.hide(true)
            }else {
                UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                self.hud.hide(true)
            }
        }
    }
    // MARK: - 附件的图片显示
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PicCollectionViewCell
        cell.backgroundColor = UIColor.white
        var photo = imageArray.object(at: (indexPath as NSIndexPath).row) as! String
        photo = photo.replacingOccurrences(of: "../..", with: "")
        let imageurl = server + priImg + photo + "&width=300&mode=W"
        cell.imageUrl = imageurl
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        index1 = String((indexPath as NSIndexPath).row)
        showBigImage()
        
    }
    /**
     显示大图
     
     - parameter notification:
     */
    func showBigImage(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url") as! String
        let index = UInt(dic.object(forKey: "index") as! String)
        let array = imageUrl.components(separatedBy: "|") as NSArray
        let array1 = NSMutableArray()
        array1.addObjects(from: array as! [Any])
        let n = array1.count
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = array1.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")
//            let user = getUserPojo()
//            if self.apiulr != "" {
//                url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
//            }
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    /**
     显示大图
     
     */
    func showBigImage(){
        let n = imageArray.count
        let index = UInt(index1)
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = imageArray.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    func numberOfPhotos(in photoBrowser: MWPhotoBrowser!) -> UInt {
        return UInt(photoArray.count)
    }
    func photoBrowser(_ photoBrowser: MWPhotoBrowser!, photoAt index: UInt) -> MWPhotoProtocol! {
        
        if index < UInt(photoArray.count) {
            
            return photoArray.object(at: Int(index)) as! MWPhotoProtocol
            
        }
        
        return nil;
    }
    
    
    // MARK: - 评论回复相关－－tableview
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let dic: NSDictionary = commentArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
        let url = dic.object(forKey: "Url") as! String
        var msg = dic.object(forKey: "Msg") as! String
        msg = msg.removingPercentEncoding!
        
        var height: CGFloat = 70 + getLabelHeight(msg, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 90) + 10
        if url.characters.count == 0{
            //文字
            
        }else if url.hasSuffix(".jpg"){
            //图片
            let array = url.components(separatedBy: "|") as NSArray
            
            height += getPicCollectionHeight(array) + 10
        }else if url.hasSuffix(".mp3"){
            //语音
            
            height += 50
        }
        return height
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 50))
        view.backgroundColor = UIColor.white
        
        let line = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 10))
        line.backgroundColor = UIColor.init(hexString: "f0f0f0", alpha: 1)
        view.addSubview(line)
        
        let label = UILabel.init(frame: CGRect(x: 10, y: 10, width: screenW-20, height: 40))
        label.text = "评论 \(commentArray.count)"
        label.textColor = UIColor.black
        label.font = UIFont.systemFont(ofSize: 14)
        view.addSubview(label)
        
        let line2 = UIView.init(frame: CGRect(x: 0, y: 49, width: screenW, height: 1))
        line2.backgroundColor = UIColor.init(hexString: "eeeeee", alpha: 1)
        view.addSubview(line2)
        
        return view
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dic = commentArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
        let cell: HomeWorkContentTableViewCell = HomeWorkContentTableViewCell(dictionary: dic, reuseIdentifier: "HomeWorkContentTableViewCellIdentifier" )
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        return cell
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
